package com.huineta.business.common.security.services;

import com.huineta.business.modules.sys.domain.SysMenu;
import com.huineta.business.modules.sys.domain.SysRole;
import com.huineta.business.modules.sys.domain.SysUser;
import com.huineta.business.modules.sys.mapper.SysUserMapper;
import com.huineta.business.modules.sys.service.ISysUserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Author:       Dmm Lee< bclassline@gmail.com >
 * Date:         2022/11/28
 * Description:  Security 用户服务实现
 */
@Component
public class SecurityUserService implements UserDetailsService {

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private ISysUserService sysUserService;

    /**
     * 加载用户信息
     * */
    @Override
    public SecurityUser loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserMapper.selectByUsername(username);
        if(sysUser==null) {
            throw new UsernameNotFoundException("USERNAME NOT SUPPORT");
        }
        sysUser.setAuthorities(loadAuthorities(sysUser.getId()));
        sysUser.setRoles(loadRoles(sysUser.getId()));
        return sysUser;
    }

    public Set<? extends GrantedAuthority> loadAuthorities(String userId){
        Set<SimpleGrantedAuthority> authoritySet = new HashSet<>();
        List<SysMenu> powers = sysUserService.permission(userId);
        for (SysMenu power : powers) {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(power.getCode());
            authoritySet.add(authority);
        }
        return authoritySet;
    }

    public List<SysRole> loadRoles(String userId) {
        return sysUserService.role(userId);
    }
}
